package com.butang.controller;

import com.butang.pojo.Dept;
import com.butang.pojo.DeptLog;
import com.butang.pojo.Result;
import com.butang.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * ClassName: DeptController
 * Package: com.butang.controller
 * Description:
 *
 * @Author BuTang
 * @Create 2023/7/9 23:10
 * @Version 1.0
 */
@Slf4j
@RestController
public class DeptController {
    @Autowired
    private DeptServiceImpl deptService;
    @Autowired
    private EmpServiceImpl empService;
    @Autowired
    private DeptLogServiceImpl deptLogService;



    @GetMapping("/depts")
    public Result list() {
        log.info("查询所有部门");
        List<Dept> list = deptService.list();
        return Result.success(list);
    }

    @DeleteMapping("/depts/{id}")
    @Transactional(rollbackFor = Exception.class)//出现所有异常都会回滚
    public Result delete(@PathVariable Integer id){
        log.info("删除部门:{}",id);
        deptService.delete(id);
        empService.delete(id);
//        try {
//            if (true){
//                throw new RuntimeException();
//            }
//        } catch (RuntimeException e) {
//            throw new RuntimeException(e);
//        }finally {

        DeptLog deptLog = new DeptLog(null, LocalDateTime.now(),"删除部门"+id);
        deptLogService.insert(deptLog);
//        }
        return Result.success();
    }

    @PostMapping("/depts")
    public Result insert(@RequestBody Dept dept){
        deptService.insert(dept);
        return Result.success();
    }

    @GetMapping("/depts/{id}")
    public Result idSelect(@PathVariable Integer id){
        Dept dept = deptService.idSelect(id);
        return Result.success(dept);
    }

    @PutMapping("/depts")
    public Result update(@RequestBody Dept dept){
        log.info("进入/depts");
        deptService.update(dept)   ;
        return Result.success();
    }
}
